package interceptor

import (
	"gitee.com/go-boot/boot-interfaces/ihttp"
	"time"
)

type LoggerInterceptor struct{}

func NewLogger() *LoggerInterceptor {
	return &LoggerInterceptor{}
}

func (l *LoggerInterceptor) Order() int {
	return 1
}

func (l *LoggerInterceptor) Name() string {
	return "logger-interceptor"
}

func (l *LoggerInterceptor) Before(ctx ihttp.IHttpContext) bool {
	ctx.Set("time", time.Now())
	return true
}

func (l *LoggerInterceptor) After(ctx ihttp.IHttpContext) bool {
	start, ok := ctx.Get("time")
	if !ok {
		return true
	}
	startTime := start.(time.Time)
	endTime := time.Now()
	milliseconds := endTime.Sub(startTime).Milliseconds()
	ctx.Log().InfoF("请求路径: %s, 请求方式: %s, 耗时: %sms", ctx.Path(), ctx.Method(), milliseconds)
	return true
}
